package com.lagou.zk.mysql;
import cn.hutool.json.JSONUtil;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ZK_Jdbc_demo {
    private  static JDBCParam jdbcParam= new JDBCParam("jdbc:mysql://linux123:3306/mysql?characterEncoding=utf-8&useSSL=false", "root","12345678");
    private  static Connection conn = null;
    public static void main(String[] args) throws InterruptedException {
        //获取到zkClient
        final ZkClient zkClient = new ZkClient("linux121:2181");
        System.out.println("zkclient is ready");
        //设置自定义序列化类型,否则会报错
        zkClient.setZkSerializer(new ZkStrSerializer());
        getNewConnection();
        //判断节点是否存在，不存在创建节点并赋值
        final boolean exists = zkClient.exists("/jdbc");
        if(!exists) {
            zkClient.createPersistent("/jdbc", JSONUtil.toJsonStr(jdbcParam));
        }
        //System.out.println(JSONObject.fromObject(jdbcParam));
        //注册监听器，节点数据改变的类型，接收通知后的处理逻辑定义
        zkClient.subscribeDataChanges("/jdbc", new IZkDataListener() {
            public void handleDataChange(String path, Object o) throws Exception {
                //定义接收通知之后的处理逻辑
                System.out.println(path +" data is change, new data" + o);
                String s = o.toString();
                JDBCParam jp = JSONUtil.toBean(s, JDBCParam.class);
                jdbcParam.setUrl(jp.getUrl());
                jdbcParam.setName(jp.getName());
                jdbcParam.setPasswd(jp.getPasswd());
                getNewConnection();
            }

            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path +" is deleted!!");
            }


        });

        //zkClient.writeData("/jdbc", JSONUtil.toJsonStr(jdbcParam));
        Thread.sleep(1000);

        Thread.sleep(Integer.MAX_VALUE);

    }

     public static void getNewConnection() {
         try {
                 if (conn!=null) {
                    conn.close();
             }
                 conn = DriverManager.getConnection(jdbcParam.getUrl(), jdbcParam.getName(), jdbcParam.getPasswd());
                 System.out.println(String.format("连接成功：host：%s name:%s password:%s",jdbcParam.getUrl() , jdbcParam.getName() , jdbcParam.getPasswd()));
         } catch (SQLException e) {
             e.printStackTrace();
         }
         }
    }
